package com.hit.aircraftwar.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

import com.hit.aircraftwar.R;
import com.hit.aircraftwar.application.RankAdapter;
import com.hit.aircraftwar.dao.Record;
import com.hit.aircraftwar.dao.RecordsDAO;
import com.hit.aircraftwar.dao.RecordsDaoImpl;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Objects;

public class RankingListActivity extends AppCompatActivity {
    private Button delete;
    private Button return_main;
    private LinkedList<Record> records;
    private ListView rankView;
    private RecordsDAO recordsDAO;
    private RankAdapter rankAdapter;
    private int index = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rank);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        Objects.requireNonNull(getSupportActionBar()).hide();
        //初始化
        recordsDAO = new RecordsDaoImpl();
        recordsDAO.setName();
        records = new LinkedList<>();
        return_main = findViewById(R.id.return_main);
        delete = findViewById(R.id.delete);
        rankView = findViewById(R.id.list_view);
//        获取数据
        try {
            records = recordsDAO.getAllRecord();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //将listview与适配器绑定
        rankAdapter = new RankAdapter(RankingListActivity.this, records);
        rankView.setAdapter(rankAdapter);


        //点击事件：返回到主菜单
        return_main.setOnClickListener(view ->{
            Intent intent = new Intent(RankingListActivity.this, MainActivity.class);
            startActivity(intent);
        });

        //点击事件：删除并更新排行榜
        delete.setOnClickListener(view ->{
            try {
                if(records.size() > 0 && index < records.size()) {
                    recordsDAO.removeRecord(records.get(index).getTimeInfo());
                    records.remove(index);
                    rankAdapter.notifyDataSetChanged();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        //设置点击列表中的项目，获取对应行数
        rankView.setOnItemClickListener((parent, view, position, id) -> index = position);
    }
}

